"""
@Time : 2022/9/16 18:08 
@Author : ls
@DES: 
"""
import requests
from main import application
from fastapi import WebSocket
from fastapi import APIRouter
from typing import List
from config import settings
from models.dict_obj import DictObj

router = APIRouter()


class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()


@application.websocket("/inventory/realTime")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    await websocket.send_text("当前websocket的clientId")
    await websocket.send_text('Websocket已连接成功，正在等待用户指令！')
    base_url = settings.PATH_CONFIG.BASEURL
    # 设置回调函数，将 websocket 内存地址作为参数，传入回调中
    # try:
    #     while True:
    #         data = await websocket.receive_text()
    #         yard_id = websocket.query_params['coalYardId']
    #         # yard_id = 11
    #         if data == 'start':
    #             await websocket.send_text("接受的CoalYardId为：" + str(yard_id))
    #             await websocket.send_text("正在通过指令进行传输，请稍后...")
    #             url = base_url + '/coal/coalYard/realTime/coalYardInfo?coalYardId=' + str(yard_id)
    #             response = requests.get(url).json()
    #             # DictOBj将一个dict转化为一个对象，方便以属性的方式访问
    #             coal_yard_dict = response['data']
    #             coal_yard_obj = DictObj(coal_yard_dict)
    #             # logger.info(response)
    #             # 这一步很重要: 给websocket添加煤场属性，值为煤场对象
    #             websocket.coalYard = coal_yard_obj
    #             # websocket.__setattr__('coalYard', coal_yard_obj)
    #             # 判断是否正在盘煤（如果请求参数中的雷达没有全部停止，则发送等待信号）
    #             # radars = coal_yard_obj.coalRadarList
